import axios from 'axios'
import store from '@/store'
//import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

// 创建一个axios的实例(对象)
const service = axios.create({
  baseURL: "http://39.108.97.241:8081", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // 请求的超时时间
})

// 请求拦截
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Content-Type'] = 'application/json;charset=utf-8';
      config.headers['Authorization']=store.getters.token;
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应的拦截
service.interceptors.response.use(
  //返回响应数据
  response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }

        if (res.code !== 200){
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 2 * 1000
            })
        }
        return res;
    },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service